package com.face.ineterceptor;


import com.face.service.AccountService;
import com.face.util.CookieUtil;
import com.face.util.StringConstans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class WechatInterceptor implements HandlerInterceptor {

    @Autowired
    AccountService accountService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws IOException {

        String openid = CookieUtil.getCookieValue(httpServletRequest, StringConstans.WECHAT_OPENID);

        if (openid != null && !StringUtils.isEmpty(openid) && openidIsBand(openid)) {
            return true;
        }

        httpServletResponse.setHeader("Content-type", "text/html;charset=UTF-8");
        httpServletResponse.getWriter().write("{\"message\":\"未登录\",\"code\":\"302\"}");
        return false;
    }

    private boolean openidIsBand(String openid) {
        String username = accountService.findUsernameByOpenid(openid);
        return (username != null && !StringUtils.isEmpty(username));
    }
}
